import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { FormItemProps } from "@/views/system/generator/utils/types";
import editForm from "@/views/system/generator/form.vue";
import dayjs from "dayjs";
import type { PaginationProps } from "@pureadmin/table";
import { message } from "@/utils/message";
import {
  generatorsAdd,
  generatorsDel,
  generatorsUpdate,
  getGeneratorsList
} from "@/api/system/generator";
import { addDialog } from "@/components/ReDialog/index";
import { deviceDetection } from "@pureadmin/utils";

export function useGenerator() {
  const form = reactive({
    title: "",
    pageSize: 10,
    currentPage: 1
  });
  const loading = ref(true);
  const isShow = ref(false);
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  // 表格列
  const columns: TableColumnList = [
    {
      label: "业务名",
      prop: "title"
    },
    {
      label: "模块名",
      prop: "routerPath"
    },
    {
      label: "数据库表名",
      prop: "tableName"
    },
    {
      label: "模型名",
      prop: "modelName"
    },
    {
      label: "创建时间",
      prop: "createdAt",
      minWidth: 160,
      formatter: ({ createdAt }) =>
        dayjs(createdAt).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  // 分页
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 查询列表
  async function onSearch() {
    loading.value = true;
    const { data } = await getGeneratorsList(toRaw(form));
    dataList.value = [...data.lists];
    pagination.total = data.pagination.total;
    pagination.pageSize = data.pagination.pageSize;
    pagination.currentPage = data.pagination.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  // 重置
  async function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    await onSearch();
  }

  // 新增 修改
  async function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}代码生成`,
      props: {
        formInline: {
          id: row?.id || 0,
          tableName: row?.tableName || "",
          modelName: row?.modelName || "",
          fields: row?.fields || [],
          title: row?.title || [],
          routerPath: row?.routerPath || []
        }
      },
      width: "60%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`您${title}了名称为${curData.title}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(async valid => {
          if (valid) {
            for (let i = 0; i < curData.fields.length; i++) {
              if (!curData.fields[i].title) {
                message("字段名不能为空", { type: "error" });
                return;
              }
              if (!curData.fields[i].type) {
                message("字段类型不能为空", { type: "error" });
                return;
              }
              if (!curData.fields[i].name) {
                message("属性不能为空", { type: "error" });
                return;
              }
              console.log(curData.fields[i].type);
            }
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              await generatorsAdd(curData);
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              await generatorsUpdate(Object.assign({ id: row.id }, curData));
              chores();
            }
          }
        });
      }
    });
  }

  // 删除
  async function handleDelete(row) {
    await generatorsDel({ id: row.id });
    message(`您删除了名称为${row.title}的这条数据`, { type: "success" });
    await onSearch();
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  // handle pageSize
  async function handleSizeChange(val: number) {
    form.pageSize = val;
    await onSearch();
  }

  // handle currentPage
  async function handleCurrentChange(val: number) {
    form.currentPage = val;
    await onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  onMounted(async () => {
    await onSearch();
  });

  return {
    form,
    isShow,
    columns,
    loading,
    openDialog,
    onSearch,
    rowStyle,
    dataList,
    pagination,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange,
    handleDelete,
    resetForm
  };
}
